<!doctype html>


<html>
  <head>
    <meta charset="utf-8">
    <title>Emscripten:Export1</title>
  </head>
  <body>
  <script type="module">
        import YUVSurfaceShader from './YUVSurfaceShader.js'
        import Texture from './Texture.js'

        let videoStreamId = 1

        let canvas = null
        /**
         * @type {YUVSurfaceShader}
         */
        let yuvSurfaceShader = null
        let yTexture = null
        let uTexture = null
        let vTexture = null

        /**
         * @type {Array<Uint8Array>}
         */
        const h264samples = []

        /**
         * @param {Uint8Array}buffer
         * @param {number}width
         * @param {number}height
         */
        function onPicture (yBuffer,uBuffer,vBuffer, width, height) {
    
          canvas.width = width
          canvas.height = height

		  //const maxXTexCoord = sourceWidth / stride
		  //const maxYTexCoord = sourceHeight / height
          // we upload the entire image, including stride padding & filler rows. The actual visible image will be mapped
          // from texture coordinates as to crop out stride padding & filler rows using maxXTexCoord and maxYTexCoord.

          yTexture.image2dBuffer(yBuffer, width, height)
          uTexture.image2dBuffer(uBuffer, width, height)
          vTexture.image2dBuffer(vBuffer, width, height)

          yuvSurfaceShader.setTexture(yTexture, uTexture, vTexture)
          yuvSurfaceShader.updateShaderData({ w: width, h: height }, { maxXTexCoord:1,maxYTexCoord:1 })
          yuvSurfaceShader.draw()
        }

        function initWebGLCanvas () {
          canvas = document.createElement('canvas')
          const gl = canvas.getContext('webgl')
          yuvSurfaceShader = YUVSurfaceShader.create(gl)
          yTexture = Texture.create(gl, gl.LUMINANCE)
          uTexture = Texture.create(gl, gl.LUMINANCE)
          vTexture = Texture.create(gl, gl.LUMINANCE)

          document.body.append(canvas)
        }
        function main () {
          window.onPicture = onPicture;
          initWebGLCanvas()
        }
        main()
    </script>  
   <script type="text/javascript">
    Module = {};
	
    // var ws = new WebSocket("wss://echo.websocket.org");
    /*
    ws.onerror = function(e) {
      console.log('已关闭');
    };
    ws.onopen = function(e) {
      console.log('握手成功');
      ws.send('123456789');
    }
    ws.onclose = function() {
      console.log('已关闭');
    }
    ws.onmessage = function(e) {
      console.log('收到消息');
      console.log(e);
    }
    */
    
	
	var demuxBuffer = null;
    var lockReconnect = false;//避免重复连接
    var wsUrl = "ws://127.0.0.1:28802";
    var ws;
    var tt;
    function createWebSocket() {
      try {
        ws = new WebSocket(wsUrl);
        init();
      } catch(e) {
        console.log('catch');
        reconnect(wsUrl);
      }
    }
    function init() {
      ws.onclose = function () {
        console.log('链接关闭');
        reconnect(wsUrl);
      };
      ws.onerror = function() {
        console.log('发生异常了');
        reconnect(wsUrl);
      };
      ws.onopen = function () {
        //心跳检测重置
        ws.send("RTMP_OPEN:192.168.0.254");
      };
      ws.onmessage = function (event) {
        //拿到任何消息都说明当前连接是正常的
		    let reader = new FileReader();
            reader.onload = () => {
                if(Module && Module.onLoadFlag){
                  let sample = new Uint8Array(reader.result);
                  for(let i=0;i<188;i++){
                    Module._setPacket(i,sample[i]);
                  }
                  Module._demuxer();
                }
            };
        reader.readAsArrayBuffer(event.data);
        //console.log('接收到消息');
        //heartCheck.start();
      }
    }
    function reconnect(url) {
      if(lockReconnect) {
        return;
      };
      lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      tt && clearTimeout(tt);
      tt = setTimeout(function () {
        createWebSocket(url);
        lockReconnect = false;
      }, 4000);
    }
    //心跳检测
    var heartCheck = {
      timeout: 3000,
      timeoutObj: null,
      serverTimeoutObj: null,
      start: function(){
        //console.log('start');
        var self = this;
        this.timeoutObj && clearTimeout(this.timeoutObj);
        this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
        this.timeoutObj = setTimeout(function(){
          //这里发送一个心跳，后端收到后，返回一个心跳消息，
          //console.log('55555');
          self.serverTimeoutObj = setTimeout(function() {
            //console.log(111);
            //console.log(ws);
            ws.close();
            // createWebSocket();
          }, self.timeout);
 
        }, this.timeout)
      }
    }
    createWebSocket(wsUrl);
  </script>
    <script>

Module.onRuntimeInitialized = function() { //此时才能获得完整Module对象
		console.log(Module);
		//console.log(Module._add(12, 1.0));
		Module.onDemux = function(array){
			//console.info(u8Array.length);
			//window.onPicture(arrayY,arrayU,arrayV,width,height);
			let postBuffer = new Uint8Array(array.length);
			for(let i=0;i<array.length;i++){
				postBuffer[i] = array[i];
			}
			Module.worker.postMessage(postBuffer.buffer, [postBuffer.buffer]);
		}
		Module.worker = new Worker("test.js");
		Module.worker.onmessage = function (evt) {
					console.log('master reveived msg: ',evt.data)
		}
        //var ab = new ArrayBuffer(1);
            // 使用transportObject
        //Module.worker.postMessage(ab, [ab]);

		Module.onLoadFlag = true;
    }
    </script>
    <script src="tsdemux.js"></script>
  </body>
</html>